<!DOCTYPE html>
<html>

<head>
  <style>
    #mydiv {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>

<body>

  <div id="mydiv"></div>

  <script>
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    var box = document.getElementById("mydiv");
    box.onmousedown = dragMouseDown;

    function dragMouseDown(e) {
      console.log(1);

      e = e || window.event;
      e.preventDefault();
      pos3 = e.clientX;
      pos4 = e.clientY;
      document.onmouseup = closeDragElement;
      document.onmousemove = elementDrag;
    }

    function elementDrag(e) {
      console.log(2);

      e = e || window.event;
      e.preventDefault();
      pos1 = pos3 - e.clientX;
      pos2 = pos4 - e.clientY;
      pos3 = e.clientX;
      pos4 = e.clientY;
      e.target.style.top = (box.offsetTop - pos2) + "px";
      e.target.style.left = (box.offsetLeft - pos1) + "px";
    }

    function closeDragElement() {
      console.log(3);
      document.onmouseup = null;
      document.onmousemove = null;
    }
  </script>

</body>

</html>